import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components'
import {AtButton, AtIcon} from 'taro-ui'
import IntegraList from '../../components/integral/integral'
import {user} from '../../../utils/user.service'
import {http} from '../../../utils/http'
import {vcmonitor} from "../../../utils/tools";
import {GET_TOTAL_INTEGRAL, GET_MY_INTEGRAL, SINGIN} from '../../../constants/api'
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import Water from "../../components/water-mark/index";
import './integral.scss'

interface myIntegral {
  firstPage: boolean
  lastPage: boolean
  list: any
  pageNumber: number
  pageSize: number
  totalPage: number
  totalRow: number
}

export default class Integral extends Component {
  state: {
    loadMoreStatus: "more" | "loading" | "noMore"
    totalIntegral: {
      integral: number
      isSign: boolean
    }
    records: any
    submiting: boolean
  } = {
    loadMoreStatus: 'loading',
    totalIntegral: {
      integral: 0,
      isSign: true,
    },
    records: [],
    submiting: false,
  }

  UNSAFE_componentWillMount() {
    vcmonitor(this, false)
  }

  async componentDidShow() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    await this.getData()
  }

  page = 1

  async getData(): Promise<void> {
    Taro.showLoading({title: '加载中...'})
    const totalIntegral = await http.get(GET_TOTAL_INTEGRAL, {})
    const myIntegral: any = await http.get<myIntegral>(GET_MY_INTEGRAL, {nowPage: 1})
    if (totalIntegral && myIntegral) {
      if (myIntegral.lastPage) {
        this.setState({totalIntegral, records: myIntegral.list, loadMoreStatus: 'noMore'})
      } else {
        this.setState({totalIntegral, records: myIntegral.list, loadMoreStatus: 'more'})
      }
    }
    setTimeout(() => {
      Taro.hideLoading()
    }, 100)
  }

  async getIntegral(page) {
    const integral: any = await http.get<myIntegral>(GET_MY_INTEGRAL, {nowPage: page})
    if (integral) {
      if (integral.lastPage) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return integral.list
    } else {
      return []
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const old = this.state.records
      const records = await this.getIntegral(this.page)
      this.setState({records: [...old, ...records]})
    }
  }

  async signIn() {
    this.setState({submiting: true}, async () => {
      const ret = await http.post(SINGIN, {})
      if (ret !== false) {
        Taro.showToast({title: '签到成功'})
        await this.getData()
        Taro.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
      }
    })
  }

  async gotoPage(url) {
    const isLogin = await user.checkLogin()
    if (isLogin) {
      Taro.navigateTo({
        url
      })
    } else {
      user.jumpLogin()
    }
  }

  render() {
    const {records, totalIntegral, submiting} = this.state
    return (
      <View className='my-integral-root'>
        <Water />
        <GzhAuth />
        <View className='points-rules' onClick={this.gotoPage.bind(this, '/main/my/integral/rules')}>
          <AtIcon size='18px' prefixClass='car' value='iconmaidan1' color='#999' />
          <View>{process.env.integralName}规则</View>
        </View>
        <View className='head'>
          <View className='tips'>当前{process.env.integralName}</View>
          <View className='num' style={`color: ${process.env.mainColor}`}>{totalIntegral.integral}</View>
          <View className='btn'>
            <AtButton type='secondary'
              customStyle={`color:#fff;border-color:${process.env.mainColor};background-color: ${process.env.mainColor}`}
              disabled={submiting || totalIntegral.isSign} circle
              onClick={this.signIn.bind(this)}
            >签到</AtButton>
          </View>
        </View>
        <View className='content'>
          {records.length > 0 && records.map((item, index) => <View key={index} className='item'>
            <IntegraList name={item.config_name} total={item.score} time={item.add_date} mode='integral' />
          </View>)}
        </View>
      </View>
    )
  }
}
